package FilterDesigners.Tests.Butterworth;

import FilterDesigners.Butterworth.LowpassButterworthFilter;
import junit.framework.TestCase;
import java.lang.Math;

public class LowpassButterworthFilterTest extends TestCase{
	
	private LowpassButterworthFilter lPBFilter;

	double W1 = 4000*Math.PI; 
	double W2 = 10000*Math.PI; 
	double K1 = 2; 
	double K2 = 20; 
	
	public void setUp() {
		lPBFilter = new LowpassButterworthFilter(W1, W2, K1, K2);
	}

	public void testOrder() {
		// The math for calculating the filter order is:
		// expectedOrderNumerator = Math.log10( ( Math.pow(10.0,(K1/10.0)) - 1)/( Math.pow(10.0, (K2/10.0)) -1) );
		// expectedOrderDenominator = 2.0*Math.log10(W1/W2);
		// dOrder = expectedOrderNumerator/expectedOrderDenominator;
		// nOrder = (int) Math.ceil(dOrder);
		assertEquals(3, lPBFilter.ORDER); //For the specifications, an order of 3 (rounded up from 2.8) should be expected.
	}
	
	public void testCalculatePoleAngle() {
		
		assertEquals(0.0, lPBFilter.getPoleAngles().get(0));
		assertEquals(60.0, lPBFilter.getPoleAngles().get(1));
		LowpassButterworthFilter lPBFilter2 = new LowpassButterworthFilter(W1, W2, K1, K2*1.2); //Create a 4th order filter, for checking getPoleAngles() for an even order.
		assertEquals(22.5, lPBFilter2.getPoleAngles().get(0));
		assertEquals(67.5, lPBFilter2.getPoleAngles().get(1));
	}
	
	public void testCalculateQValues() {
		assertEquals(1.0, lPBFilter.getQValues().get(0), 0.0000001);
		
	}
	
	public void testCalculate3dBFreq() {
		double wcPrimeExpected = W1/Math.pow(Math.pow(10.0, K1/10.0) - 1, 1.0/(2.0*lPBFilter.ORDER));
		double wc2PrimeExpected = W2/Math.pow(Math.pow(10.0, K2/10.0) - 1, 1.0/(2.0*lPBFilter.ORDER));
		double expectedFreq = Math.sqrt(wcPrimeExpected*wc2PrimeExpected);
		assertEquals(expectedFreq, lPBFilter.get3dBFreq());
		assertEquals(14167, lPBFilter.get3dBFreq(), 1.0); // Compare to hand calculation with acceptable error of 1.0
	}
	
	public void testCalculateNormalizedComponents() {
		assertEquals(1.0, lPBFilter.getNormalizedComponents().get(0), 0.0000001);
		assertEquals(2.0*lPBFilter.getQValues().get(0), lPBFilter.getNormalizedComponents().get(1), 0.0000001);
		assertEquals(1.0, lPBFilter.getNormalizedComponents().get(2), 0.0000001);
		assertEquals(1.0/(2.0*lPBFilter.getQValues().get(0)), lPBFilter.getNormalizedComponents().get(3), 0.0000001);
	}
	
}
